package com.woniuxy.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.purchase.entity.dto.AddSupplierDTO;
import com.woniuxy.purchase.entity.dto.SelectPurchaseDTO;
import com.woniuxy.purchase.entity.pojo.BuyPurchase;
import com.woniuxy.purchase.entity.vo.AllPurchaseVO;
import com.woniuxy.purchase.entity.vo.DemandDetailsVO;
import com.woniuxy.purchase.entity.vo.PurchaseDetailsVO;
import com.woniuxy.purchase.mapper.BuyPurchaseMapper;
import com.woniuxy.purchase.service.BuyDemandService;
import com.woniuxy.purchase.service.BuyPurchaseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BuyPurchaseServiceImpl implements BuyPurchaseService {
    @Resource
    private BuyPurchaseMapper buyPurchaseMapper;
    @Resource
    private BuyDemandService buyDemandService;

    @Override
    public void updatePurchaseStateById(Integer state, Integer id) {
        BuyPurchase buyPurchase = new BuyPurchase();
        buyPurchase.setId(id);
        buyPurchase.setState(state);
        buyPurchaseMapper.updateById(buyPurchase);
        BuyPurchase result = buyPurchaseMapper.selectById(id);
        //如果采购表状态为2则开始采购,同时为需求表修改状态为3(采购中)
        //如果采购表状态为3则开始已完成,同时为需求表修改状态为4(采购中)
        if(state >=2) {
            buyDemandService.updateDemandStateById(state + 2, result.getDemandId());
        }
    }

    @Override
    public Page<BuyPurchase> findPurchaseByCondition(SelectPurchaseDTO dto) {
        Page<BuyPurchase> page = new Page<>(dto.getCurrent(),dto.getPageSize());
        LambdaQueryWrapper<BuyPurchase> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dto.getState()!=null,BuyPurchase::getState,dto.getState());
        return buyPurchaseMapper.selectPage(page,lqw);
    }

    @Override
    public List<PurchaseDetailsVO> findDemandDetails(Integer id) {
        //1.根据id查询到商品数据
        List<DemandDetailsVO> demandDetails = buyDemandService.findDemandDetails(id);
        //2.赋值给采购表详情
        return BeanUtil.copyToList(demandDetails, PurchaseDetailsVO.class);
    }

    @Override
    public Integer updatePurchaseById(AddSupplierDTO dto) {
        //1.为采购单添加供应商并修改状态为未开始
        BuyPurchase buyPurchase = new BuyPurchase();
        buyPurchase.setSupplierName(dto.getName());
        buyPurchase.setId(dto.getId());
        buyPurchase.setState(1);
        //2.根据purchase的id查询demand的id
        BuyPurchase result = buyPurchaseMapper.selectById(dto.getId());
        // 修改需求单状态2(已分配)
        buyDemandService.updateDemandStateById(2,result.getDemandId());
        return buyPurchaseMapper.updateById(buyPurchase);
    }

    @Override
    public List<AllPurchaseVO> findAllPurchase(Integer id) {
        return buyPurchaseMapper.findAllPurchase(id);
    }


}
